<?php

namespace common\behavior\CommonMessagePushing;


use common\model\EntityModel;
use common\model\UserModel;
use common\observer\RelationChangeAutoAssembleCheck;
use common\service\BehaviorService;
use common\service\ChatService;
use common\service\EntityService;
use common\service\OptionsService;
use common\service\ProjectService;
use Webman\Stomp\Client;

/**
 * 实体关联变更 消息通知
 */
class EntityRelationChangeBehavior
{
    /**
     * @param $params
     * @return void
     */
    public function run($params)
    {
        /***********  预处理开始  ************/
        $params = BehaviorService::getInstance()->dealParam(
            $params,
            [
                'entity' => '',
                'module_code' => 'strval',
                'added' => '',
                'deleted' => '',
            ],
            [
                'entity' => [],
                'module_code' => '',
                'added' => [],
                'deleted' => [],
            ],
            'data',
            ['type' => 'entity_relation_change'],
        );
        /***********  行为判断  ************/
        if ($params === false) {
            return;
        }
        /***********  变量迁移  ************/
        list($entity, $moduleCode, $added, $deleted) = $params;
        if (empty($entity) || empty($moduleCode)) {
            return;
        }
        /***********  预处理结束  ************/

        /***********  原逻辑迁移  ************/


        $upstreamEntity = null;
        if (in_array($moduleCode, ['asset', 'level', 'design'])) {
            // 资产线 查找概念
            if ($moduleCode === 'design') {
                $upstreamEntity = $entity;
            } else {
                $upstreamEntity = EntityService::getInstance()->getUpstreamEntity($entity);
            }
        } else {
            // 镜头线
            if ($moduleCode === 'storyboard') {
                $upstreamEntity = $entity;
            } else {
                $upstreamEntity = EntityService::getInstance()->getUpstreamEntity($entity);
            }
            try {
                $operator = model(UserModel::class)->field('id,name,union_id')->where(['id' => \request()->getUserId()])->find();
                $chat = ChatService::getInstance()->createEntityChat($upstreamEntity);
                $entityName = get_chat_entity_task_name($upstreamEntity);
                $message = [
                    'type' => 'association_entity_task_message',
                    'replace' => [
                        'operator' => ['id' => $operator['union_id'], 'name' => $operator['name']],
                        'entity_name' => $entityName,
                    ]
                ];
                ChatService::getInstance()->pushEntityTaskMessage($message, $chat);
            } catch (\Throwable $e) {
                trace(format_exception_info($e), 'ERR');
            }
        }

        $taskName = '【' . $entity['initial_episode_code'] . '/' . $entity['showings_number'] . '/' . $entity['name'] . '】';

        $noteText = '任务' . $taskName;

        $taskEntityText = [];
        if (!empty($added)) {
            $addEntityNameList = model(EntityModel::class)
                ->where(['id' => ['IN', implode(',', $added)]])
                ->field('name')
                ->column('name');
            if (!empty($addEntityNameList)) {
                $taskEntityText[] = '新增关联:' . implode(',', $addEntityNameList);
            }
        }

        if (!empty($deleted)) {
            $deleteEntityNameList = model(EntityModel::class)
                ->where(['id' => ['IN', implode(',', $deleted)]])
                ->field('name')
                ->column('name');
            if (!empty($deleteEntityNameList)) {
                $taskEntityText[] = '移除关联:' . implode(',', $deleteEntityNameList);
            }
        }

        // 记录异常通知
        $queueData = [
            'module_code' => 'entity',
            'type' => 'relation_change',
            'info' => implode(';', $taskEntityText),
            'data' => $entity,
        ];
        Client::send("abnormal_info_store", build_queue_data_with_xu($queueData));

        // 查询该实体关联的任务，所在的环节列表
        $entityRelateStepCategoryList = EntityService::getInstance()->getEntityRelateTask($entity, ['task.step_category_id']);

        $taskRelatePeoples = EntityService::getInstance()->getEntityRelatePeople($entity, false);
        $peopleIdList = array_column($taskRelatePeoples, 'union_id');
        $peopleIdListCc = [];
        if (!empty($entityRelateStepCategoryList)) {
            // 抄送给这些环节 配置的【环节制片】
            $peopleIdListCc = ProjectService::getInstance()->projectConfigMessageReceiverUnionIdList([
                'project_id' => $entity['project_id'],
                'step_category_id' => array_column($entityRelateStepCategoryList, 'step_category_id'),
                'role_code_list' => ['step_producer'],
            ]);
        }
        $peopleIdList = array_unique(array_merge($peopleIdList, $peopleIdListCc));

        if (empty($peopleIdList)) {
            return;
        }
        $templateId = OptionsService::getInstance()->getEntityTaskRemindCommonTemplateId();
        $notifyParam = [
            'first' => '任务信息变更',
            'note_text' => $noteText,
            'remark' => "请及时查看",
            'tenant_id' => $upstreamEntity['tenant_id'],
            'project_id' => $upstreamEntity['project_id'],
            'entity_id' => $upstreamEntity['id'],
            'module_code' => in_array(module_by_id($upstreamEntity['module_id'])['code'], ['design', 'level', 'asset']) ? 'design' : 'storyboard',
            'message_key' => 'entity_relation_change',
        ];
        $messageGenerated = [];
        foreach ($taskEntityText as $entityText) {
            foreach ($peopleIdList as $people) {
                $messageGenerated[] = [
                    "param" =>
                        array_replace($notifyParam, [
                            'note_text' => $notifyParam['note_text'] . $entityText,
                        ]),
                    'receiver' => $people,
                    'template_id' => $templateId,
                    'content_type' => 'card_message',
                    'notice_type' => 'message_demand',
                    'is_popup' => 1,
                    'message_key' => 'entity_relation_change',
                ];
            }
        }

        /***********  发送新的队列  ************/
        foreach ($messageGenerated as $message) {
            Client::send('common_message_pushing', build_queue_data_with_xu([
                'message_generated' => [$message],
            ]));
        }
        /***********  结束  ************/
    }
}
